package mirkofrancuski.battleship.game;

import java.util.Random;

import android.util.Log;

import mirkofrancuski.battleship.GameActivity;

public class Game extends Thread {
	private static final String DEBUG_TAG = "DEBUG Game";
	
	
	public enum PlayerType {
		USER, COMPUTER
	};

	private Player[] players;

	private boolean end;
	private int currentPlayerIndex;

	private Coordinates currentTryShot;
	private Cell shotResult;

	public Game(Player p1, Player p2) {
		players = new Player[2];

		players[0] = p1;
		players[1] = p2;

		end = false;
		currentPlayerIndex = (new Random()).nextInt(2);
	}
	
	public Game(Player p1, Player p2, int currentPlayer, boolean isEnd){
		this(p1,p2);
		end = isEnd;
		currentPlayerIndex = currentPlayer;
	}

	@Override
	public void run() {
		PlayerType[] playerTypes = PlayerType.values();

		try {
			while (!end) {
				((GameActivity) players[0])
						.setPlayerTurn(playerTypes[currentPlayerIndex]);
				
				Log.d(DEBUG_TAG, "turn: "+playerTypes[currentPlayerIndex].toString());

				if(currentPlayerIndex == 0){
					synchronized (players[0]) {
						players[0].wait();
					}
				} else {
					sleep(1000);
				}

				currentTryShot = players[currentPlayerIndex]
						.getShotCoordinates();
				
				Log.d(DEBUG_TAG, "shot: "+currentTryShot.toString());
				
				if (currentTryShot == null)
					continue;
				shotResult = players[(currentPlayerIndex + 1) % 2]
						.takeHit(currentTryShot);
				
				Log.d(DEBUG_TAG, "result: "+shotResult.toString());
				
				if(shotResult == Cell.HIT || shotResult == Cell.MISS)			{	
					players[currentPlayerIndex].resultFromLastShot(shotResult);
				} else {
					Ship sunkenShip = players[(currentPlayerIndex + 1) % 2].getShip(shotResult);
					players[currentPlayerIndex].resultFromLastShot(sunkenShip);
				}

				end = players[0].areAllShipsSunk()
						|| players[1].areAllShipsSunk();

				Log.d(DEBUG_TAG, "end: "+end);
				
				if (shotResult != Cell.MISS)
					continue;

				currentPlayerIndex = (currentPlayerIndex + 1) % 2;
			}
		} catch (InterruptedException e) {
			//kraj
		}

		((GameActivity) players[0]).gameOver();

	}
	
	public void end() {
		this.interrupt();
	}

	public Player getWinner() {
		if (!end)
			return null;

		return players[currentPlayerIndex];
	}

	public boolean isEnd() {
		return end;
	}

	public int getCurrentPlayerIndex() {
		return currentPlayerIndex;
	}
	
	

}
